package com.feiyun.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feiyun.erp.entity.Functions;
import com.feiyun.erp.entity.Role;
import com.feiyun.erp.entity.User;
import com.feiyun.erp.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * SpringSecurity的用户查询逻辑实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名查询用户信息 select * from user where username = xxx
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //根据用户名查询用户的角色
        List<Role> roles = userMapper.selectRolesByUsername(username);
        //根据用户名查询用户的权限
        List<Functions> functions = userMapper.selectFunctionsByUsername(username);
        //定义字符串用于拼接角色和权限的名称
        StringBuilder builder = new StringBuilder();
        roles.forEach(role -> {
            //角色的名称必须以ROLE_开头
            builder.append("ROLE_"+role.getName() + ",");
        });
        functions.forEach(fun ->{
            builder.append(fun.getName() + ",");
        });
        if(builder.length() > 0){
            //删除最后的,
            builder.deleteCharAt(builder.length() - 1);
        }
        //包装到UserDetails对象中，返回
        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(builder.toString()));
    }
}
